<script setup lang="ts">
import {
  Viewer,
  UrlTemplateImageryProvider,
  ImageryLayer,
  Math,
  Cartesian3,
  OpenStreetMapImageryProvider,
  WebMapTileServiceImageryProvider,
  createOsmBuildings,
  Color,
  VerticalOrigin,
  Rectangle,
  RectangleGeometry,
  VertexFormat,
  PerInstanceColorAppearance,
  Geometry,
  GeometryInstance,
  ColorGeometryInstanceAttribute,
  Primitive,
  ScreenSpaceEventHandler,
  ScreenSpaceEventType,
Material,
} from 'cesium'
import 'cesium/Build/Cesium/Widgets/widgets.css'
import { onMounted, ref } from 'vue'
;(window as any).CESIUM_BASE_URL = '/cesium'
const contentRef = ref<HTMLDivElement>()

onMounted(() => {
  const viewer = new Viewer(contentRef.value!, {
    infoBox: false,
    /** 搜索框 */
    geocoder: false,
    /** home按钮 */
    homeButton: false,
    // 动画控件
    animation: false,
    // 全屏按钮
    fullscreenButton: false,
    // 场景模式选择器
    sceneModePicker: false,
    // 时间轴
    timeline: false,
    // 导航提示
    navigationHelpButton: false,
    // 地图选择器
    baseLayerPicker: false,
    // // 天地图矢量路径图
    // imageryProvider: new WebMapTileServiceImageryProvider({
    //   url: "http://t0.tianditu.com/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=e1b3504ab9c8245cc6b8c681e1589831",
    //   layer: "tdtBasicLayer",
    //   style: "default",
    //   format: "image/jpeg",
    //   tileMatrixSetID: "GoogleMapsCompatible",
    // }),
    // 天地图影像服务
    // imageryProvider: new WebMapTileServiceImageryProvider({
    //   url: 'http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=e1b3504ab9c8245cc6b8c681e1589831',
    //   layer: 'tdtBasicLayer',
    //   style: 'default',
    //   format: 'image/jpeg',
    //   tileMatrixSetID: 'GoogleMapsCompatible',
    //   minimumLevel: 1,
    //   maximumLevel: 18,
    // }),
    // OSM地图,
    // imageryProvider: new OpenStreetMapImageryProvider({
    //   url: "https://a.tile.openstreetmap.org/",
    // }),
    // 高德矢量地图,
    imageryProvider: new UrlTemplateImageryProvider({
      url: 'http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
      minimumLevel: 1,
      maximumLevel: 18,
    }),
    // geoServer TMS地图
    // imageryProvider: new UrlTemplateImageryProvider({
    //   url: 'http://192.168.33.48:8080/geoserver/gwc/service/tms/1.0.0/suzhou_map%3Akunshan_map@EPSG%3A3857@png/{z}/{x}/{reverseY}.png',
    //   minimumLevel: 1,
    //   maximumLevel: 18,
    // }),
  })

  // const tDProvider = new WebMapTileServiceImageryProvider({
  //   url: 'http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=e1b3504ab9c8245cc6b8c681e1589831',
  //   layer: 'tdtBasicLayer',
  //   style: 'default',
  //   format: 'image/jpeg',
  //   tileMatrixSetID: 'GoogleMapsCompatible',
  //   minimumLevel: 1,
  //   maximumLevel: 18,
  // })

  // const layer = new ImageryLayer(tDProvider, { alpha: 0.8 })
  // const layer = new ImageryLayer(
  //   new UrlTemplateImageryProvider({
  //     url: 'http://webst01.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}',
  //     minimumLevel: 1,
  //     maximumLevel: 18,
  //   }),
  //   {}
  // )

  // viewer.imageryLayers.add(layer)

  viewer.camera.setView({
    destination: Cartesian3.fromDegrees(120.980795, 31.385476, 9950000),
    orientation: {
      /** 相机朝向 */
      heading: Math.toRadians(0),
      /** 相机俯视角 */
      pitch: Math.toRadians(-70),
      /** 相机翻滚角 */
      roll: 0,
    },
  })

  viewer.entities.add({
    position: Cartesian3.fromDegrees(120.311889, 31.491064, 1000),
    point: {
      pixelSize: 20,
      color: Color.RED,
      outlineColor: Color.WHITE,
      outlineWidth: 4,
    },
  })
  viewer.entities.add({
    position: Cartesian3.fromDegrees(120.311889, 31.491064, 1200),

    label: {
      text: '无锡市政府',
      fillColor: Color.BLACK,
      font: '24px sans-serif',
    },
  })

  viewer.entities.add({
    polyline: {
      positions: Cartesian3.fromDegreesArray([-75, 15, -125, 35, -125, 25, -75, 25, -75, 55]),
      width: 4,
      material: Color.RED,
    },
  })

  // 创建几何体
  const rectangleGeometry = new RectangleGeometry({
    rectangle: Rectangle.fromDegrees(90, 20, 110, 30),
    extrudedHeight: 100,
    height: 0,
    vertexFormat: PerInstanceColorAppearance.VERTEX_FORMAT,
  })
  const rectangleGeometry2 = new RectangleGeometry({
    rectangle: Rectangle.fromDegrees(111, 20, 131, 30),
    extrudedHeight: 100,
    height: 0,
    vertexFormat: PerInstanceColorAppearance.VERTEX_FORMAT,
  })

  // 为几何体添加属性
  const rectangleInstance = new GeometryInstance({
    id: 'greenGeo',
    geometry: rectangleGeometry,
    attributes: {
      color: ColorGeometryInstanceAttribute.fromColor(Color.GREEN.withAlpha(0.5)),
    },
  })
  // 为几何体添加属性
  const rectangleInstance2 = new GeometryInstance({
    id: 'blueGeo',
    geometry: rectangleGeometry2,
    attributes: {
      color: ColorGeometryInstanceAttribute.fromColor(Color.BLUE.withAlpha(0.5)),
    },
  })

  // 创建图元
  const rectanglePrimitive = new Primitive({
    geometryInstances: [rectangleInstance, rectangleInstance2],
    appearance: new PerInstanceColorAppearance({
      flat: true,
    }),
  })

  setInterval(() => {
    rectanglePrimitive.getGeometryInstanceAttributes('blueGeo').color = ColorGeometryInstanceAttribute.toValue(
      Color.fromRandom({ alpha: 0.5 })
    )
  }, 2000)

  viewer.scene.primitives.add(rectanglePrimitive)

  const handler = new ScreenSpaceEventHandler(viewer.canvas)

  handler.setInputAction((e: ScreenSpaceEventHandler.PositionedEvent) => {
    const res = viewer.scene.pick(e.position)
    if (typeof res?.id === 'string') {
      const prim = res.primitive as Primitive
      prim.getGeometryInstanceAttributes(res.id).color = ColorGeometryInstanceAttribute.toValue(Color.WHITE)
    }
  }, ScreenSpaceEventType.LEFT_CLICK)

  handler.setInputAction((e: ScreenSpaceEventHandler.MotionEvent) => {
    const res = viewer.scene.pick(e.endPosition)
    if (typeof res?.id === 'string') {
      viewer.canvas.style.cursor = 'pointer'
      console.log()
    } else {
      viewer.canvas.style.cursor = 'default'
    }
  }, ScreenSpaceEventType.MOUSE_MOVE)
  ;(viewer.cesiumWidget.creditContainer as HTMLDivElement).style.display = 'none'
})
</script>

<template>
  <div class="play-terrain" ref="contentRef"></div>
</template>

<style lang="scss" scoped>
.play-terrain {
  height: 100%;
  width: 100%;
}
</style>
